package com.czy.owner.ui.bottom;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.czy.owner.R;
import com.czy.owner.adapter.PersonDataAdapter;
import com.czy.owner.api.AccontInfoApi;
import com.czy.owner.api.CartCountApi;
import com.czy.owner.api.GetCustomerApi;
import com.czy.owner.api.GetSystemServiceApi;
import com.czy.owner.api.OrderCountInfoApi;
import com.czy.owner.api.UserInfoApi;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.AccountInfoModel;
import com.czy.owner.entity.MessageContacts;
import com.czy.owner.entity.OrderCountInfoModel;
import com.czy.owner.entity.PersonDataModel;
import com.czy.owner.entity.PushGoodsModel;
import com.czy.owner.entity.UserInfoModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.api.BaseResultEntity;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.net.utils.JsonUtil;
import com.czy.owner.net.utils.MyLoadView;
import com.czy.owner.ui.BaseFragment;
import com.czy.owner.ui.accountbalance.StoreBalanceActivity;
import com.czy.owner.ui.address.AddressActivity;
import com.czy.owner.ui.archive.CarDossierActivity;
import com.czy.owner.ui.archive.TestingListActivity;
import com.czy.owner.ui.collection.CollectionActivity;
import com.czy.owner.ui.coupons.CouponsActivity;
import com.czy.owner.ui.hotshop.ShoppingCartActivity;
import com.czy.owner.ui.message.ChatActivity;
import com.czy.owner.ui.order.OrderActivity;
import com.czy.owner.ui.packagecardproject.MyPackageCardProjectActivity;
import com.czy.owner.ui.setting.SettingActivity;
import com.czy.owner.ui.userinfo.AboutUsActivity;
import com.czy.owner.ui.userinfo.FeedBackActivity;
import com.czy.owner.ui.userinfo.GrowthValueActivity;
import com.czy.owner.ui.userinfo.UserInfoActivity;
import com.czy.owner.ui.workorder.SubscribeOrdelActivity2;
import com.czy.owner.utils.GsonUtils;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.utils.glide.GlideUtils;
import com.czy.owner.widget.DialogCall;
import com.czy.owner.widget.MyScrollView;
import com.czy.owner.widget.NoScrollRecyclerView;
import com.czy.owner.widget.RoundImageView;
import com.easemob.cases.MessageHelper;
import com.easyrecycleview.adapter.RecyclerArrayAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.domain.EaseUser;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.czy.owner.R.id.tv_refund;
import static com.czy.owner.R.id.tv_stay_evaluate;
import static com.czy.owner.R.id.tv_stay_goods_receivers;
import static com.czy.owner.R.id.tv_stay_install;
import static com.czy.owner.R.id.tv_stay_payment;
import static com.hyphenate.easeui.domain.EaseUser.USER_TYPE_SYSTEM;


/**
 * Created by wangyng on 2017/52 0002.
 * 我的
 */

public class PersonFragment extends BaseFragment implements MyScrollView.ScrollViewLine {
    //    @BindView(R.id.tv_title_center)
//    TextView tvTitleCenter;
    @BindView(R.id.roundimgview)
    RoundImageView mRoundimgview;
    @BindView(R.id.tv_user_phone)
    TextView tvUserPhone;
    @BindView(R.id.tv_user_group)
    TextView tvUserGroup;
    @BindView(R.id.ll_user_item)
    LinearLayout llUserItem;
    @BindView(R.id.tv_store_bannce)
    TextView tvStoreBannce;
    @BindView(R.id.tv_card_package)
    TextView tvCardpPackage;
    @BindView(R.id.myscrollview)
    MyScrollView myScrollView;
    //    @BindView(R.id.line_headview)
//    LinearLayout lineHeadView;
    @BindView(tv_stay_payment)
    TextView tvStayPayment;
    @BindView(tv_stay_goods_receivers)
    TextView tvStayGoodsReceivers;
    @BindView(tv_stay_install)
    TextView tvStayInstall;
    @BindView(tv_stay_evaluate)
    TextView tvStayEvaluate;
    @BindView(tv_refund)
    TextView tvRefund;
    @BindView(R.id.person_rv_list)
    NoScrollRecyclerView personRvList;

    @BindView(R.id.tv_tip_stay_payment)
    TextView tvTipStayPayment;
    @BindView(R.id.tv_tip_stay_good_receivers)
    TextView tvTipStayGoodReceivers;
    @BindView(R.id.tv_tip_stay_install)
    TextView tvTipStayInstall;
    @BindView(R.id.tv_tip_stay_evaluate)
    TextView tvTipStayEvaluate;
    @BindView(R.id.tv_tip_refund)
    TextView tvTipRefund;


    @BindView(R.id.tv_tip_car_count)
    TextView tvTipCarCount;
    @BindView(R.id.linear_user_group)
    LinearLayout linearUserGroup;
    Unbinder unbinder;
    private PersonDataAdapter personDataAdapter;
    private boolean scrollviewOldL = false;
    private double storeBalance = 0.00;
    private int packageCount;
    private Intent intent = null;
    private MyLoadView mLoadView;

//    @Override
//    public void onHiddenChanged(boolean hidden) {
//        super.onHiddenChanged(hidden);
//        if (!hidden) {
//            setTitleLayout(lineHeadView);
//            if (scrollviewOldL) {
//                lineHeadView.getBackground().setAlpha(255);
//            } else {
//                lineHeadView.getBackground().setAlpha(0);//开始是透明的
//            }
//            myScrollView.setScrollViewLine(this);
//
//        }
//
//
//    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_person;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        if (!UserHelper.getInstance().isLogined()) {
            return;
        }
//        setTitleLayout(lineHeadView);
//        lineHeadView.getBackground().setAlpha(0);//开始是透明的
        myScrollView.setScrollViewLine(this);
        personRvList.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        personDataAdapter = new PersonDataAdapter(getActivity());
        personRvList.setAdapter(personDataAdapter);


        personDataAdapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener<PersonDataModel>() {
            @Override
            public void onItemClick(View view, int position, PersonDataModel model) {

                if (model.getName().equals("工单记录")) {
                    startActivity(new Intent(getActivity(), SubscribeOrdelActivity2.class));
                }
                if (model.getName().equals("联系客服")) {
                    //getSystemService();
//                    getCustomer(getActivity());
                    pushGoods();
                }
                if (model.getName().equals("收货地址")) {
                    startActivity(new Intent(getActivity(), AddressActivity.class));
                }
                if (model.getName().equals("意见反馈")) {
                    Intent ti = new Intent(getActivity(), FeedBackActivity.class);
                    ti.putExtra("feedback", "system");
                    startActivity(ti);
                }
                if (model.getName().equals("关于我们")) {
                    startActivity(new Intent(getActivity(), AboutUsActivity.class));
                }
                if (model.getName().equals("车检单")) {
//                    PhoneUtils.ShowToastMessage(getActivity(), "车检单");
                    startActivity(new Intent(getActivity(), TestingListActivity.class));
                }


            }
        });
    }


    @Override
    protected void updateViews() {

    }

    @OnClick({R.id.line_update_user_info, R.id.img_setting, R.id.line_store_bannce
            , R.id.line_card_package, R.id.tv_shopping_car, R.id.tv_collection
            , R.id.tv_car_archives, R.id.tv_coupons, R.id.relative_all_order
            , R.id.tv_stay_payment, R.id.tv_stay_goods_receivers, R.id.tv_stay_install
            , R.id.tv_stay_evaluate, R.id.tv_refund, R.id.linear_user_group})
    public void myOnClick(View view) {
        switch (view.getId()) {
            //TODO 成长值 Growth value
            case R.id.linear_user_group:
                intent = new Intent(getActivity(), GrowthValueActivity.class);
                startActivity(intent);
                break;
            case R.id.line_update_user_info:
                intent = new Intent(getActivity(), UserInfoActivity.class);
                startActivity(intent);
                break;
            case R.id.img_setting:
                intent = new Intent(getActivity(), SettingActivity.class);
                startActivity(intent);
//                intent = new Intent(getActivity(), ParityActivity.class);
//                startActivity(intent);
                break;
            case R.id.line_store_bannce:
                intent = new Intent(getActivity(), StoreBalanceActivity.class);
                startActivity(intent);
                break;
            case R.id.line_card_package:
                intent = new Intent(getActivity(), MyPackageCardProjectActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_shopping_car:
                startActivity(new Intent(getActivity(), ShoppingCartActivity.class));
                break;
            case R.id.tv_collection:
                intent = new Intent(getActivity(), CollectionActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_car_archives:
                intent = new Intent(getActivity(), CarDossierActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_coupons:
                intent = new Intent(getActivity(), CouponsActivity.class);
                startActivity(intent);
                break;
            case R.id.relative_all_order:
                intent = new Intent(getActivity(), OrderActivity.class);
                intent.putExtra("currentId", 0);
                startActivity(intent);
                break;
            case R.id.tv_stay_payment:
                intent = new Intent(getActivity(), OrderActivity.class);
                intent.putExtra("currentId", 1);
                startActivity(intent);
                break;
            case R.id.tv_stay_goods_receivers:
                intent = new Intent(getActivity(), OrderActivity.class);
                intent.putExtra("currentId", 2);
                startActivity(intent);
                break;
            case R.id.tv_stay_install:
                intent = new Intent(getActivity(), OrderActivity.class);
                intent.putExtra("currentId", 3);
                startActivity(intent);
                break;
            case R.id.tv_stay_evaluate:
                intent = new Intent(getActivity(), OrderActivity.class);
                intent.putExtra("currentId", 4);
                startActivity(intent);
                break;
            case R.id.tv_refund:
                intent = new Intent(getActivity(), OrderActivity.class);
                intent.putExtra("currentId", 5);
                startActivity(intent);
                break;
        }
    }


    //用户信息Api
    private void userInfoData() {
        UserInfoApi userInfoApi = new UserInfoApi(new HttpOnNextListener<UserInfoModel>() {
            @Override
            public void onNext(UserInfoModel model) {
                setUserInfo(model);
            }

            @Override
            public void onCacheNext(String cache) {
                super.onCacheNext(cache);
                Gson gson = new Gson();
                Type type = new TypeToken<BaseResultEntity<UserInfoModel>>() {
                }.getType();
                BaseResultEntity<UserInfoModel> userInfoCache = gson.fromJson(cache, type);
                setUserInfo(userInfoCache.getData());
            }


            @Override
            public void onError(Throwable e) {
                super.onError(e);
            }


        }, (RxAppCompatActivity) getContext());
        userInfoApi.setSession(UserHelper.getInstance().getSession(getActivity()));
        HttpManager manager = HttpManager.getInstance();
        manager.doHttpDeal(userInfoApi);


    }


    private void setUserInfo(UserInfoModel model) {
        GlideUtils.loadImage(getActivity(), model.getUserLogo(), mRoundimgview, new GlideUtils.ImageLoadListener<String, GlideDrawable>() {
            @Override
            public void onLoadingComplete(String uri, ImageView view, GlideDrawable resource) {

            }

            @Override
            public void onLoadingError(String source, Exception e) {

            }
        }, R.mipmap.person_default_icon, R.mipmap.person_default_icon);
        tvUserPhone.setText(model.getNickName());
        tvUserGroup.setText("成长值:  " + model.getGrowthValue());
    }


    //用户账户信息Api
    private void accountInfo() {
        AccontInfoApi accontInfoApi = new AccontInfoApi(new HttpOnNextListener<AccountInfoModel>() {
            @Override
            public void onNext(AccountInfoModel model) {
                setAccountInfo(model);
            }

            @Override
            public void onCacheNext(String cache) {
                super.onCacheNext(cache);
                Gson gson = new Gson();
                Type type = new TypeToken<BaseResultEntity<AccountInfoModel>>() {
                }.getType();
                BaseResultEntity<AccountInfoModel> accountInfoCache = gson.fromJson(cache, type);
                setAccountInfo(accountInfoCache.getData());
            }


            @Override
            public void onError(Throwable e) {
                super.onError(e);
            }
        }, (RxAppCompatActivity) getContext());
        accontInfoApi.setSession(UserHelper.getInstance().getSession(getActivity()));
        // accontInfoApi.setStoreId(SharedPreferencesUtils.getParam(getActivity(), UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "");
        HttpManager manager = HttpManager.getInstance();
        manager.doHttpDeal(accontInfoApi);

    }

    private void setAccountInfo(AccountInfoModel model) {
        storeBalance = model.getStoreBalance();
        tvStoreBannce.setText(String.format("%.2f", storeBalance) + "元");
        packageCount = model.getPackageCount();
        tvCardpPackage.setText(packageCount + "");
    }


    //    订单数量
    private void orderCountInfo() {
        OrderCountInfoApi orderCountInfoApi = new OrderCountInfoApi(new HttpOnNextListener<OrderCountInfoModel>() {
            @Override
            public void onNext(OrderCountInfoModel data) {
                int waitPay = data.getWaitPay();
                if (waitPay != 0) {
                    tvTipStayPayment.setVisibility(View.VISIBLE);
                    tvTipStayPayment.setText(waitPay + "");
                } else {
                    tvTipStayPayment.setVisibility(View.INVISIBLE);
                }
                int delivery = data.getDelivery();
                if (delivery != 0) {
                    tvTipStayGoodReceivers.setVisibility(View.VISIBLE);
                    tvTipStayGoodReceivers.setText(delivery + "");
                } else {
                    tvTipStayGoodReceivers.setVisibility(View.INVISIBLE);
                }
                int toInstall = data.getToInstall();
                if (toInstall != 0) {
                    tvTipStayInstall.setVisibility(View.VISIBLE);
                    tvTipStayInstall.setText(toInstall + "");
                } else {
                    tvTipStayInstall.setVisibility(View.INVISIBLE);
                }
                int completed = data.getCompleted();
                if (completed != 0) {
                    tvTipStayEvaluate.setVisibility(View.VISIBLE);
                    tvTipStayEvaluate.setText(completed + "");
                } else {
                    tvTipStayEvaluate.setVisibility(View.INVISIBLE);
                }
                int refund = data.getRefund();
                if (refund != 0) {
                    tvTipRefund.setVisibility(View.VISIBLE);
                    tvTipRefund.setText(refund + "");
                } else {
                    tvTipRefund.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void onCacheNext(String cache) {
                super.onCacheNext(cache);
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
            }
        }, (RxAppCompatActivity) getContext());
        orderCountInfoApi.setSession(UserHelper.getInstance().getSession(getActivity()));
        orderCountInfoApi.setStoreId(SharedPreferencesUtils.getParam(getActivity(), UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "");
        orderCountInfoApi.setCloseMall(UserHelper.getInstance().isCloseMall() + "");
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(orderCountInfoApi);

    }


    @Override
    public void onResume() {
        super.onResume();
        if (!UserHelper.getInstance().isLogined()) {
            return;
        }
        MyLog.e("yang", "onResume");
        personDataAdapter.clear();
        personDataAdapter.addAll(initDataList());
        userInfoData();
        accountInfo();
        orderCountInfo();
        getCarCount();


    }

    public List<PersonDataModel> initDataList() {
        List<PersonDataModel> list = new ArrayList<>();
        list.add(new PersonDataModel("工单记录"));
        if (!UserHelper.getInstance().isCloseMall()) {
            list.add(new PersonDataModel("联系客服"));
        }
        list.add(new PersonDataModel("收货地址"));
        list.add(new PersonDataModel("意见反馈"));
        list.add(new PersonDataModel("关于我们"));
        list.add(new PersonDataModel("车检单"));
        if (!UserHelper.getInstance().isCloseMall()) {
            list.add(new PersonDataModel(""));
            list.add(new PersonDataModel(""));
        } else {
            list.add(new PersonDataModel(""));
            list.add(new PersonDataModel(""));
            list.add(new PersonDataModel(""));
        }
//

        return list;
    }


    protected void setTitleLayout(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getActivity().getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            view.setPadding(0, 0, 0, 0);
        }
    }


    @Override
    public void onScrollChanged(int l, int t, int oldl, int oldt) {
        if (oldt < 10) {
//            tvTitleCenter.setVisibility(View.GONE);
            scrollviewOldL = false;
//            lineHeadView.getBackground().setAlpha(0);
//        } else if (oldt < 40 && oldt > 10) {
//            lineHeadView.getBackground().setAlpha(oldt / 8);
//        } else if (oldt < 70 && oldt > 40) {
//            lineHeadView.getBackground().setAlpha(oldt / 7);
//        } else if (oldt < 100 && oldt > 70) {
//            lineHeadView.getBackground().setAlpha(oldt / 6);
//        } else if (oldt < 130 && oldt > 100) {
//            lineHeadView.getBackground().setAlpha(oldt / 5);
//        } else if (oldt < 150 && oldt > 130) {
//            lineHeadView.getBackground().setAlpha(oldt / 4);
//        } else if (oldt < 180 && oldt > 150) {
//            lineHeadView.getBackground().setAlpha(oldt / 3);
//        } else if (oldt < 200 && oldt > 180) {
//            lineHeadView.getBackground().setAlpha(oldt / 2);
//        } else if (oldt >= 200) {
//            scrollviewOldL = true;
//            lineHeadView.getBackground().setAlpha(255);
////            tvTitleCenter.setVisibility(View.VISIBLE);
//        } else {
//            scrollviewOldL = false;
        }

    }

    public void getCustomer(final Context mContext) {
//        if (mLoadView == null)
//            mLoadView = new MyLoadView(mContext, "正在加载");
//        mLoadView.ShowLoadView();
//        String url = Constants.APP_API_BASE + Constants.OWN_ORDERS_GETCUSTOMER;
//        RequestParams params = new RequestParams(url);
//        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(getActivity()).getSession());
//        params.addBodyParameter("storeId", 0 + "");
////        PhoneUtils.ShowToastMessage(this, storeId+"");
//        params.addBodyParameter("type", "goods");
//        x.http().post(params, new Callback.CommonCallback<String>() {
//
//            @Override
//            public void onSuccess(String result) {
//                //这个方法不提示错误信息。复制注意
//                String data = PhoneUtils.checkResponseFlagLogin((Activity) mContext, result);
//                try {
//                    if (!StringUtils.isEmpty(data)) {
//                        MessageContacts messageContacts = GsonUtils.fromJson(data, MessageContacts.class);
//
////
//                    } else {
//                        PhoneUtils.ShowToastMessage(mContext, mContext.getResources().getString(R.string.customer_service_toast));
//                        pushGoods();
//                    }
//                } catch (Exception e) {
//                    Log.e("King", "解析失败!");
//                    e.printStackTrace();
//                }
//
//
//            }
//
//            @Override
//            public void onError(Throwable ex, boolean isOnCallback) {
//
//            }
//
//            @Override
//            public void onCancelled(CancelledException cex) {
//
//            }
//
//            @Override
//            public void onFinished() {
//                mLoadView.CancleLoadView();
//            }
//        });

        GetCustomerApi getCustomerApi = new GetCustomerApi(new HttpOnNextListener<MessageContacts>() {
            @Override
            public void onNext(MessageContacts messageContacts) {
                if (!TextUtils.isEmpty(messageContacts.getImKey())) {
                    EaseUser easeUser = new EaseUser(messageContacts.getImKey());
                    easeUser.setNick(messageContacts.getName());
                    easeUser.setAvatar(messageContacts.getUserLogo());
                    easeUser.setEmployeeId("" + messageContacts.getStoreEmployeesId());
                    easeUser.setPhone(messageContacts.getPhone());
                    easeUser.setUserType(USER_TYPE_SYSTEM);
                    MessageHelper.getInstance().saveContact(easeUser);

                    //EMClient.getInstance().chatManager().importMessages(msgs);
                    if (EMClient.getInstance().isConnected()) {
                        String st4 = "您好，请问有什么可以帮助您的？";
                        // your application was accepted
                        EMMessage msg = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
                        msg.setChatType(EMMessage.ChatType.Chat);
                        msg.setFrom(messageContacts.getImKey());
                        msg.setTo(EMClient.getInstance().getCurrentUser());
                        msg.setMsgId(UUID.randomUUID().toString());
                        msg.addBody(new EMTextMessageBody(st4));
                        msg.setStatus(EMMessage.Status.SUCCESS);
                        // save accept message
                        EMClient.getInstance().chatManager().saveMessage(msg);
                    }
                    Intent intent = new Intent(mContext, ChatActivity.class);
                    intent.putExtra(EaseConstant.EXTRA_USER_ID, messageContacts.getImKey());
                    mContext.startActivity(intent);
                }

            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
//                PhoneUtils.ShowToastMessage(mContext, e.getMessage());
            }
        }, (RxAppCompatActivity) mContext);
        getCustomerApi.setSession(UserHelper.getInstance().getSessionInfoModel(mContext).getSession());
        getCustomerApi.setStoreId("0");
        getCustomerApi.setType("goods");
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(getCustomerApi);
    }

    //推送客服
    public void pushGoods() {
        if (mLoadView == null)
            mLoadView = new MyLoadView(mContext, "正在加载");
        mLoadView.ShowLoadView();
        String url = Constants.APP_API_BASE + Constants.OWN_PUSHGOODS;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(getActivity()).getSession());
        params.addBodyParameter("goodsId", 0 + "");
        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                MyLog.e("hep", "" + result);
                //这个方法不提示错误信息。复制注意
                String data = PhoneUtils.checkResponseFlagLogin((Activity) mContext, result);
                boolean flag = JsonUtil.getJsonValuesBoolean(result, "flag");
                int errorCode = JsonUtil.getJsonValuesInt(result, "errorCode");

                try {
                    PushGoodsModel pushGoodsModel = GsonUtils.fromJson(data, PushGoodsModel.class);
                    if (flag) {
                        if (!TextUtils.isEmpty(pushGoodsModel.getImKey())) {
//                            EaseUser easeUser = new EaseUser(messageContacts.getImKey());
//                            easeUser.setNick(messageContacts.getName());
//                            easeUser.setAvatar(messageContacts.getUserLogo());
//                            easeUser.setEmployeeId("" + messageContacts.getStoreEmployeesId());
//                            easeUser.setPhone(messageContacts.getPhone());
//                            easeUser.setUserType(USER_TYPE_SYSTEM);
//                            MessageHelper.getInstance().saveContact(easeUser);

                            //EMClient.getInstance().chatManager().importMessages(msgs);
//                            if (EMClient.getInstance().isConnected()) {
//                                String st4 = "您好，请问有什么可以帮助您的？";
//                                // your application was accepted
//                                EMMessage msg = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
//                                msg.setChatType(EMMessage.ChatType.Chat);
//                                msg.setFrom(pushGoodsModel.getImKey());
//                                msg.setTo(EMClient.getInstance().getCurrentUser());
//                                msg.setMsgId(UUID.randomUUID().toString());
//                                msg.addBody(new EMTextMessageBody(st4));
//                                msg.setStatus(EMMessage.Status.SUCCESS);
//                                // save accept message
//                                EMClient.getInstance().chatManager().saveMessage(msg);
//                            }
                            Intent intent = new Intent(mContext, ChatActivity.class);
                            intent.putExtra(EaseConstant.EXTRA_USER_ID, pushGoodsModel.getImKey());
                            mContext.startActivity(intent);
                        }
                    } else if (errorCode != 110) {
                        PhoneUtils.ShowToastMessage(mContext, mContext.getResources().getString(R.string.customer_service_toast));

                    }
                } catch (Exception e) {
                    Log.e("King", "解析失败!");
                    e.printStackTrace();
                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mLoadView.CancleLoadView();
            }
        });

//        PushGoodsApi pushGoodsApi = new PushGoodsApi(new HttpOnNextListener<Object>() {
//            @Override
//            public void onNext(Object s) {
//                getCustomer(getActivity());
//            }
//
//            @Override
//            public void onError(Throwable e) {
//                super.onError(e);
//                e.printStackTrace();
//            }
//        }, (RxAppCompatActivity) getActivity());
//        pushGoodsApi.setSession(UserHelper.getInstance().getSessionInfoModel(getActivity()).getSession());
//        pushGoodsApi.setGoodsId("0");
//        HttpManager manager = HttpManager.getInstance();
//        manager.doHttpDeal(pushGoodsApi);
    }

    @Deprecated
    private void getSystemService() {
        GetSystemServiceApi mApi = new GetSystemServiceApi(new HttpOnNextListener<String>() {
            @Override
            public void onNext(String o) {
                call(o);
            }

            @Override
            public void onCacheNext(String string) {
                super.onCacheNext(string);
                Gson gson = new Gson();
                Type type = new TypeToken<BaseResultEntity<String>>() {
                }.getType();
                BaseResultEntity<String> cache = gson.fromJson(string, type);
                call(cache.getData());
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                e.printStackTrace();
            }
        }, (RxAppCompatActivity) getActivity());
        HttpManager.getInstance().doHttpDeal(mApi);
    }

    private void call(final String phoneNumber) {
        final DialogCall dialogCall = new DialogCall(getContext(), R.layout.dialog_call);
        dialogCall.setContent("" + phoneNumber).setListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PhoneUtils.checkCallPermission(getContext(), phoneNumber);
                dialogCall.dismiss();
            }
        }).show();
    }

    //    获取购物车数量
    private void getCarCount() {
        CartCountApi goodsDetailApi = new CartCountApi(new HttpOnNextListener<JsonObject>() {
            @Override
            public void onNext(final JsonObject data) {
                int cartCount = JsonUtil.getJsonValuesInt(data.toString(), "cartCount");
                MyLog.e("yang", "cartCount==" + cartCount);
                if (cartCount != 0) {
                    tvTipCarCount.setVisibility(View.VISIBLE);
                    tvTipCarCount.setText(cartCount + "");
                } else {
                    tvTipCarCount.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                PhoneUtils.ShowToastMessage(getActivity(), e.getMessage());
            }
        }, (RxAppCompatActivity) getContext());
        goodsDetailApi.setSession(UserHelper.getInstance().getSessionInfoModel(getActivity()).getSession());
        goodsDetailApi.setStoreId(SharedPreferencesUtils.getParam(getActivity(), UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "");
        goodsDetailApi.setCloseMall(UserHelper.getInstance().isCloseMall() + "");
        HttpManager manager = HttpManager.getInstance();
        manager.doHttpDeal(goodsDetailApi);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
